package com.atguigu.flink0922.chapter07;

import com.atguigu.flink0922.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/6 10:02
 */
public class Flink09_Timer_ProcessTime_Proctice {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        SingleOutputStreamOperator<WaterSensor> stream = env
            .socketTextStream("hadoop162", 9999)  // 在socket终端只输入毫秒级别的时间戳
            .map(value -> {
                String[] datas = value.split(",");
                return new WaterSensor(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
                
            });
    
        WatermarkStrategy<WaterSensor> wms = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner((element, recordTimestamp) -> element.getTs() * 1000);
        stream
            .assignTimestampsAndWatermarks(wms)
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                private long time;  // 定时器的触发时间
                private int lastVc = 0; // 上次水位
                private boolean isFirst = true; // 是否第一次
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    if (value.getVc() > lastVc) {
                        // 水位上升
                        if (isFirst) {
                            time = ctx.timestamp() + 5000L;
                            ctx.timerService().registerEventTimeTimer(time);
                            isFirst = false;
                        }
                    }else{
                        //水位下降或者不变
                        ctx.timerService().deleteEventTimeTimer(time);
    
                        time = ctx.timestamp() + 5000L;
                        ctx.timerService().registerEventTimeTimer(time);
                    }
                    lastVc = value.getVc();
                }
    
                @Override
                public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                    out.collect(ctx.getCurrentKey() + " 水位连续5s上升预警...");
                    isFirst = true;  // 修改这个值, 可以开启一个新的定时器
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
